<?php
class CommonAction extends Action {
	
	function _initialize() {
        import('@.ORG.Cookie');
		// 用户权限检查
		if (C ( 'USER_AUTH_ON' ) && !in_array(MODULE_NAME,explode(',',C('NOT_AUTH_MODULE')))) {
            import('@.ORG.RBAC');
			if (!RBAC::AccessDecision ()) {//加上权限验证
				//检查认证识别号
				if (! $_SESSION [C ( 'USER_AUTH_KEY' )]) {
					if ($this->isAjax()){
						$this->ajaxReturn(true, "", 301);
					} else {
						//跳转到认证网关
						redirect ( PHP_FILE . C ( 'USER_AUTH_GATEWAY' ) );
					}
				}
				// 没有权限 抛出错误
				if (C ( 'RBAC_ERROR_PAGE' )) {
					// 定义权限错误页面
					redirect ( C ( 'RBAC_ERROR_PAGE' ) );
				} else {
					if (C ( 'GUEST_AUTH_ON' )) {
						$this->assign ( 'jumpUrl', PHP_FILE . C ( 'USER_AUTH_GATEWAY' ) );
					}
					// 提示错误信息
					$this->error ( L ( '_VALID_ACCESS_' ) );
				}
			}
		}
	}
	public function index() {
		//列表过滤器，生成查询Map对象
		$map = $this->_search ();
		if (method_exists ( $this, '_filter' )) {
			$this->_filter ( $map );
		}
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			$this->_list ( $model, $map );
		}
		$this->display ();
		return;
	}
	/**
     +----------------------------------------------------------
	 * 取得操作成功后要返回的URL地址
	 * 默认返回当前模块的默认操作
	 * 可以在action控制器中重载
     +----------------------------------------------------------
	 * @access public
     +----------------------------------------------------------
	 * @return string
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	function getReturnUrl() {
		return __URL__ . '?' . C ( 'VAR_MODULE' ) . '=' . MODULE_NAME . '&' . C ( 'VAR_ACTION' ) . '=' . C ( 'DEFAULT_ACTION' );
	}

	/**
     +----------------------------------------------------------
	 * 根据表单生成查询条件
	 * 进行列表过滤
     +----------------------------------------------------------
	 * @access protected
     +----------------------------------------------------------
	 * @param string $name 数据对象名称
     +----------------------------------------------------------
	 * @return HashMap
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	protected function _search($name = '') {
		//生成查询条件
		if (empty ( $name )) {
			$name = $this->getActionName();
		}
        $name = $this->getActionName();
		$model = D ( $name );
		$map = array ();
		foreach ( $model->getDbFields () as $key => $val ) {
			if (isset ( $_REQUEST [$val] ) && $_REQUEST [$val] != '') {
				$this->assign($val, $_REQUEST [$val]);
				$map [$val] = array ('like','%' . $_REQUEST [$val] . '%' );
			}
		}
		
		return $map;

	}

	/**
     +----------------------------------------------------------
	 * 根据表单生成查询条件
	 * 进行列表过滤
     +----------------------------------------------------------
	 * @access protected
     +----------------------------------------------------------
	 * @param Model $model 数据对象
	 * @param HashMap $map 过滤条件
	 * @param string $sortBy 排序
	 * @param boolean $asc 是否正序
     +----------------------------------------------------------
	 * @return void
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	protected function _list($model, $map, $sortBy = '', $asc = false) {
		//排序字段 默认为主键名
		if (!empty ( $_REQUEST ['_order'] )) {
			$order = $_REQUEST ['_order'];
		} else {
			$order = ! empty ( $sortBy ) ? $sortBy : $model->getPk ();
		}
		//排序方式默认按照倒序排列
		//接受 sost参数 0 表示倒序 非0都 表示正序
		if (isset ( $_REQUEST ['_sort'] )) {
//			$sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
			$sort = $_REQUEST ['_sort'] == 'asc' ? 'asc' : 'desc';
		} else {
			$sort = $asc ? 'asc' : 'desc';
		}
		//取得满足条件的记录数
		$count = $model->where ( $map )->count ( 'id' );
		if ($count > 0) {
			import ( "@.ORG.Page" );
			//创建分页对象
			if (! empty ( $_REQUEST ['numPerPage'] )) {
				$listRows = $_REQUEST ['numPerPage'];
			} else {
				$listRows = 5;
			}
			//得到当前页号
			if (! empty ( $_REQUEST ['pageNum'] )) {
				$pageNum = $_REQUEST ['pageNum'];
			} else {
				$pageNum = 1;
			}
			$p = new Page ( $count, $listRows );
			//分页查询数据
			$voList = $model->where($map)->order( "`" . $order . "` " . $sort)->page($pageNum . ',' . $p->listRows)->select ( );

			//echo $model->getlastsql();
			//分页跳转的时候保证查询条件
			foreach ( $map as $key => $val ) {
				if (! is_array ( $val )) {
					$p->parameter .= "$key=" . urlencode ( $val ) . "&";
				}
			}
			$p->setConfig('header','条');
			$p->setConfig('first','首页');
			$p->setConfig('last','尾页');
			$p->setConfig('theme', "<div data-role='button' data-theme='a'>共%totalRow%  %header%  第%nowPage%/%totalPage% 页   %upPage% %downPage% %first%    %linkPage%   %end%</div>");
			//分页显示
			$page = $p->show ();
			//列表排序显示
			$sortImg = $sort; //排序图标
			$sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
			$sort = $sort == 'desc' ? 1 : 0; //排序方式
			//模板赋值显示
			$this->assign ( 'list', $voList );
			$this->assign ( 'sort', $sort );
			$this->assign ( 'order', $order );
			$this->assign ( 'sortImg', $sortImg );
			$this->assign ( 'sortType', $sortAlt );
			$this->assign ( "page", $page );
		}
		
		$this->assign ( 'totalCount', $count );
		$this->assign ( 'numPerPage', $p->listRows );
		$this->assign ( 'currentPage', !empty($_REQUEST[C('VAR_PAGE')])?$_REQUEST[C('VAR_PAGE')]:1);
			
		Cookie::set ( '_currentUrl_', __SELF__ );
		return;
	}

	function insert() {
		//B('FilterString');
		$name=$this->getActionName();
		$model = D ($name);
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		$info=$this->getType($name);
		
		//保存当前数据对象
		$list=$model->add ();
		if ($list!==false) { //保存成功
			$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->insertLog('添加','操作'.$info.'编号为'.$list.'的数据成功');
			//$this->success('添加成功','__URL__/index');
			$this->redirect($name.'/index');
			//$this->ajaxReturn (1,'新增成功!',200);
		} else {
			//失败提示
			$this->insertLog('添加','操作'.$info.'编号为'.$list.'的数据失败');
			//$this->ajaxReturn (1,'新增失败!',300);
			$this->error ( $model->getError () );
		}
	}

	public function add() {
		$this->display ();
	}

	function read() {
		$this->edit ();
	}

	function edit() {
		$name=$this->getActionName();
		$model = M ( $name );
		$id = $_REQUEST [$model->getPk ()];
		$vo = $model->getById ( $id );
		$this->assign ( 'vo', $vo );
		$this->display ();
	}

	function update() {
		//B('FilterString');
		$name=$this->getActionName();
		$model = D ( $name );
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		$info=$this->getType($name);
		// 更新数据
		$list=$model->save ();
		$pk=$model->getPk();
		$id= $_REQUEST [$pk];
		if (false !== $list) {
			
			$this->insertLog('修改','操作'.$info.'编号为'.$id.'的数据成功');
			//成功提示
			//$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
			//$this->success('修改成功','__URL__/index');
			$this->redirect($name.'/index');
			//$this->ajaxReturn (1,'编辑成功!',200);
		} else {
			//错误提示
			$this->insertLog('修改','操作'.$info.'编号为'.$id.'的数据失败');
			$this->error ( $model->getError () );
		}
	}
	/**
     +----------------------------------------------------------
	 * 默认删除操作
     +----------------------------------------------------------
	 * @access public
     +----------------------------------------------------------
	 * @return string
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	public function delete() {
		//删除指定记录
		$name=$this->getActionName();
		$info=$this->getType($name);
		$model = M ($name);
		if (! empty ( $model )) {
			$pk = $model->getPk ();
			//$id = $_REQUEST [$pk];
			$id = $_REQUEST ['ids'];
			if (isset ( $id )) {
				$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
				//$list=$model->where ( $condition )->setField ( 'status', - 1 );
				$list=$model->where ( $condition )->setField ( 'removed', 2 );//删除的数据显示到回收站中
				if ($list!==false) {
					$this->insertLog('删除','操作'.$info.'编号为'.$id.'的数据成功');
					//$this->ajaxReturn (1,'删除成功!',200);
					$this->success('删除成功','__URL__/index',false);
				} else {
					$this->insertLog('删除','操作'.$info.'编号为'.$id.'的数据失败');
					//$this->ajaxReturn (1,'删除失败!',300);
					$this->error('删除失败','__URL__/index',false);
				}
			} else {
				//$this->ajaxReturn (1,'非法操作!',200);
				$this->error('非法操作','__URL__/index',false);
			}
		}
	}
	public function foreverdelete() {
		//删除指定记录
		$name=$this->getActionName();
		$info=$this->getType($name);
		$model = D ($name);
		if (! empty ( $model )) {
			$pk = $model->getPk ();
			$id = $_REQUEST ['ids'];
			if (isset ( $id )) {
				$condition = array ($pk => array ('in', explode ( ',', $id ) ) );
				if (false !== $model->where ( $condition )->delete ()) {
					$this->insertLog('彻底删除','操作'.$info.'编号为'.$id.'的数据成功');
					$this->success('删除成功','__URL__/index',false);
					//$this->ajaxReturn (1,'删除成功!',200);
				} else {
					$this->insertLog('彻底删除','操作'.$info.'编号为'.$id.'的数据失败');
					$this->error('删除失败','__URL__/index',false);
					//$this->ajaxReturn (1,'删除失败!',300);
				}
			} else {
				$this->error('非法操作','__URL__/index',false);
				//$this->ajaxReturn (1,'进行删除操作出现非法操作!',200);
			} 
		}
	}

	public function clear() {
		//删除指定记录
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			if (false !== $model->where ( 'status=-1' )->delete ()) {
				$this->assign ( "jumpUrl", $this->getReturnUrl () );
				$this->success ( L ( '_DELETE_SUCCESS_' ) );
			} else {
				$this->error ( L ( '_DELETE_FAIL_' ) );
			}
		}
		$this->forward ();
	}
	/**
     +----------------------------------------------------------
	 * 默认禁用操作
	 *
     +----------------------------------------------------------
	 * @access public
     +----------------------------------------------------------
	 * @return string
     +----------------------------------------------------------
	 * @throws FcsException
     +----------------------------------------------------------
	 */
	public function forbid() {
		$name=$this->getActionName();
		$info=$this->getType($name);
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_REQUEST [$pk];
		$condition = array ($pk => array ('in', $id ) );
		$list=$model->forbid ( $condition );
		if ($list!==false) {
			$this->insertLog('状态禁用','操作'.$info.'编号为'.$id.'的数据成功');
			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->ajaxReturn (1,'状态禁用成功!',200);
		} else {
			$this->insertLog('状态禁用','操作'.$info.'编号为'.$id.'的数据失败');
			$this->ajaxReturn (1,'状态禁用失败!',300);
		}
	}
	public function checkPass() {
		$name=$this->getActionName();
		$info=$this->getType($name);
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_GET [$pk];
		$condition = array ($pk => array ('in', $id ) );
		if (false !== $model->checkPass( $condition )) {
			$this->insertLog('批准','操作'.$info.'编号为'.$id.'的数据成功');
			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->ajaxReturn (1,'状态批准成功!',200);
		} else {
			$this->insertLog('批准','操作'.$info.'编号为'.$id.'的数据失败');
			$this->ajaxReturn (1,'状态批准失败!',300);
		}
	}

	public function recycle() {
		$name=$this->getActionName();
		$info=$this->getType($name);
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_GET [$pk];
		$condition = array ($pk => array ('in', $id ) );
		if (false !== $model->recycle ( $condition )) {
			$this->insertLog('状态还原','操作'.$info.'编号为'.$id.'的数据成功');
			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->ajaxReturn (1,'状态还原成功!',200);
		} else {
			$this->insertLog('状态还原','操作'.$info.'编号为'.$id.'的数据失败');
			$this->ajaxReturn (1,'状态还原失败!',300);
		}
	}

	public function recycleBin() {
		$map = $this->_search ();
		$map ['status'] = - 1;
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			$this->_list ( $model, $map );
		}
		$this->display ();
	}

	/**
     +----------------------------------------------------------
	 * 默认恢复操作
	 *
     +----------------------------------------------------------
	 * @access public
     +----------------------------------------------------------
	 * @return string
     +----------------------------------------------------------
	 * @throws FcsException
     +----------------------------------------------------------
	 */
	function resume() {
		//恢复指定记录
		$name=$this->getActionName();
		$info=$this->getType($name);
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_GET [$pk];
		$condition = array ($pk => array ('in', $id ) );
		if (false !== $model->resume ( $condition )) {
			$this->insertLog('状态恢复','操作'.$info.'编号为'.$id.'的数据成功');
			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->ajaxReturn (1,'状态恢复成功!',200);
		} else {
			$this->insertLog('状态恢复','操作'.$info.'编号为'.$id.'的数据失败');
			$this->ajaxReturn (1,'状态恢复失败!',300);
		}
	}


	function saveSort() {
		$seqNoList = $_POST ['seqNoList'];
		if (! empty ( $seqNoList )) {
			//更新数据对象
		$name=$this->getActionName();
		$model = D ($name);
			$col = explode ( ',', $seqNoList );
			//启动事务
			$model->startTrans ();
			foreach ( $col as $val ) {
				$val = explode ( ':', $val );
				$model->id = $val [0];
				$model->sort = $val [1];
				$result = $model->save ();
				if (! $result) {
					break;
				}
			}
			//提交事务
			$model->commit ();
			if ($result!==false) {
				//采用普通方式跳转刷新页面
				$this->success ( '更新成功' );
			} else {
				$this->error ( $model->getError () );
			}
		}
	}
	
	/**
	 * 日志记录的插入操作
	 * $data1 操作类型
	 * $data2  操作内容
	 * 
	 */
	public function insertLog($data1,$data2)
	{
		$logmodel=M('Log');
		$map=array();
		$map['userid']=$_SESSION[C('USER_AUTH_KEY')];
		$map['username']=$_SESSION['username'];
		$map['ip']=get_client_ip();
		$map['time']=date("Y-m-d H:i:s");
		$map['oprtype']=$data1;
		$map['oprcontent']=$data2;
		if($logmodel->create($map))
		{
			$logmodel->add();
		}
		else
		 {
		 	$this->error($logmodel->getError());
		 }
		
	}
	
	/**
	 * 获得操作类型
	 */
	public function getType($name)
	{
		
		if($name=="PhoneBook")
		{
			return '通讯薄信息';
		}
		if($name=="User")
		{
			return '用户管理';
		}
		if($name=="Business")
		{
			return '业务管理';
		}
		if($name=="Contract")
		{
			return '合同管理';
		}
		if($name=="Customer")
		{
			return '客户管理';
		}
		if($name=="Department")
		{
			return '部门管理';
		}
		if($name=="Dictionary")
		{
			return '常用设置管理';
		}
		if($name=="File")
		{
			return '附件管理';
		}
		if($name=="ControlTable")
		{
			return '调度管理';
		}
		if($name=="StoreManage")
		{
			return '仓库管理';
		}
		if($name=="ShortMessage")
		{
			return '个人消息管理';
		}
		if($name=="Notice")
		{
			return '公告管理';
		}
		if($name=="Provider")
		{
			return '供应商管理';
		}
		if($name=="Carrier")
		{
			return '承运商管理';
		}
		if($name=="Node")
		{
			return '节点管理';
		}
		if($name=="Role")
		{
			return '角色管理';
		}
		if($name=="Car")
		{
			return '车辆管理';
		}
		if($name=="Brrow")
		{
			return '借款管理';
		}
		
	}
}
?>